import {observable,action} from 'mobx'

import React from 'react'
import store from '../utils/SimpleStore'
import RequestUtil from '../utils/RequestUtil';
import Api from '../utils/Api';



class UserStore {
    @observable userInfo;
    @observable isLogin;



    constructor() {

        this.isLogin = false;
        this.userInfo = null


    }

    /*
    *
    * other有几种情况:
    * home {id,nickName}
    * vip {"accountBalance": "0", "balance": "68176", "levelList": [], "myLevel": {"id": 6, "name": "6"}}
    */
    setUser(data,other){
        console.log('set user data',data)

        console.log('other',other)

        if(data){
            store.save('user',data)

            global.token = data.token
            this.userInfo = {
                mobile:data.mobile,
                password:data.password
            }
            store.save('login_info',this.userInfo)
        }

        if(other){
            this.userInfo = {
                ...this.userInfo,
                ...other
            }
        }
        this.isLogin = true

    }





    @action
    getUser(){
        store.get('user').then(res=>{
            console.log('getUser',res)
            if(res){
                this.setUser(res)
            }
        })
    }

    @action
    reset(){
        this.userInfo = null;
        this.isLogin = false

        global.token = null
    }




    @action
    logout(){
        store.delete('user')
        this.reset()
    }

    @action
    login(param,callback,errorCallback){

        RequestUtil.post(Api.login,param,false).then(res=>{
            let data = res.data
            console.log('登录成功',data)
            data.mobile = param.receiverId
            data.password = param.password
            this.setUser(data)
            callback && callback(data)
        },err=>{

            errorCallback && errorCallback(err)
        })
    }

}



const userStore =   new UserStore()

export default userStore
